import { request } from '../../request/index.js';
Page({
  data: {
    //商品详情的数据
    goods_detail:{},
  },
  onLoad: function (options) {
    const {goods_id} = options;
    this.getGoodsDetail(goods_id);
  },
  //发请求获取数据
  getGoodsDetail(goods_id) {
    request({url:"/goods/detail",data:{goods_id}})
      .then(res => {
        console.log(res);
        this.goods_info = res;
        this.setData({
          goods_detail:{
            goods_name: res.data.message.goods_name,
            goods_price:res.data.message.goods_price,
            goods_introduce:res.data.message.goods_introduce.replace(/\.webp/g,'.jpg'),
            pics:res.data.message.pics
          }
        })
      })
  },
  //发送预览效果
  handprevewImage(e) {
    const urls = this.data.goods_detail.pics.map(v => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx-wx.previewImage({
      urls,
      current
    })
  },
  handleCartAdd() {
    //1.获取缓存中的数据
    let cart = wx.getStorageSync('cart') || [];
    //2.判断商品是否存在与购物车数组中
    let index = cart.findIndex(v => v.goods_id === this.goods_info.data.message.goods_id);
    if(index == -1) {
      //为-1表示没找到，第一次添加
      this.goods_info.data.message.num = 1;
      this.goods_info.data.message.isSelected = true;
      cart.push( this.goods_info.data.message);
    }else {
      //存在商品了，只需要将商品的数量加一
      cart[index].num ++;
    }
    //将购物车数据重新添加入缓存
    wx-wx.setStorageSync('cart', cart);
    //弹出提示
    wx-wx.showToast({
      title: '添加成功',
      duration: 500,
      icon: 'success',
      mask: true
    })
  }
})